//
//  ZixunListVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/21.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON
import PullToRefresh

class ZixunListVC: UIViewController ,SliderGalleryControllerDelegate, UITableViewDelegate, UITableViewDataSource {

    static let VCID = "ZixunListVC"

    let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 200, height: 28))

    @IBOutlet weak var tableView: UITableView!
    
    let banner = SliderGalleryPresenter()
    var pageNum = 0
    var bannerModels : [YSBanner] = []
    var models:[ZixunModel] = []
    let bottomRefreher = PullToRefresh(position: .bottom)
    var listType = ZixunModel.List_ID_CHANGSHANGJIAGE
    
    deinit {
        if let head = tableView.topPullToRefresh{
            self.tableView.removePullToRefresh(at: .top)
        }
        if let btm = tableView.bottomPullToRefresh{
            self.tableView.removePullToRefresh(at: .bottom)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = true
        banner.delegate = self
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.requestBanner()
        self.setupPullToRefresh()
        self.title = "资讯列表"
        self.refresh()
        
        self.addSegeListener()
    }

    func addSegeListener() {
        self.segment.segmentTitles = ["厂家价格","热点资讯"]
        self.segment.addTarget(self, action: #selector(ZixunListVC.onChooseSegement(_:)), for: .valueChanged)
        self.navigationItem.titleView = self.segment
        self.segment.selectedSegmentIndex = 0
        
        segment.addTarget(self, action: #selector(ZixunListVC.onChooseSegement(_:)), for: .valueChanged)
    }
    
    @objc func onChooseSegement(_ sender: UISegmentedControl) {
        
        
        switch (sender.selectedSegmentIndex){
        case 0:
            listType = ZixunModel.List_ID_CHANGSHANGJIAGE
            break;
        case 1:
//            listType = ZixunModel.List_ID_SHICHANGHANGQING
//            break;
//        case 2:
            listType = ZixunModel.List_ID_REDIANZIXUN
            break;
//        case 3:
//            listType = ZixunModel.List_ID_SHICHANGGUANCHA
//            break;
        default:
            break;
        }
        
        self.refresh();
    }
    
    func setupPullToRefresh() {
        self.tableView.addPullToRefresh(PullToRefresh()) { [weak self] in
            self?.refresh()
        }
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.tableView.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }

    func refresh() {
        let params = ["type":self.listType,"page":"1"]

        _ = NetworkManager.GET(NetworkManager.ZIXUN_LIST,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let newZixuns = response.wtmList.map({ (dic) -> ZixunModel in
                    JSONDeserializer<ZixunModel>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.models.removeAll()
                self.models.append(contentsOf: newZixuns)
                self.pageNum = 2
                DispatchQueue.main.async {
                    self.stopLoading()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func stopLoading(){
        tableView.endRefreshing(at: .top)
        tableView.endRefreshing(at: .bottom)
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let params = ["type":self.listType,"page":pageNumStr]
        
        _ = NetworkManager.GET(NetworkManager.ZIXUN_LIST,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let newZixuns = response.wtmList.map({ (dic) -> ZixunModel in
                    JSONDeserializer<ZixunModel>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.models.append(contentsOf: newZixuns)
                self.pageNum += 1
                DispatchQueue.main.async {
                    self.stopLoading()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func requestBanner() {
        
        _ = NetworkManager.GET(NetworkManager.ZIXUN_Banner) { (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let pics = response.wtmList
                self.bannerModels = pics.map({ (dic) -> YSBanner in
                    JSONDeserializer<YSBanner>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.banner.setupViews()
            }
        }
    }
    
    // MARK:- banner delegate
    //获取数据源
    func galleryDataSource()->[String] {
        return self.bannerModels.map{
            $0.url
        }
    }
    //获取内部scrollerView的宽高尺寸
    func galleryScrollerViewSize()->CGSize {
        return CGSize.init(width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH * 0.432)
    }
    
    func galleryViewTapped(_ index:Int) {
        let vc:ImageViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
        vc.imageUrl = self.bannerModels[index].url
        self.navigationController?.pushViewController(vc, animated: true)
    }

    // MARK :- tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count + 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return Const.SCREEN_WIDTH * 0.432 + Const.ONE_PIXEL;
        }else {
            let zixun = models[indexPath.row - 1]
            return self.heightOfZixun(zixun)
        }
    }
    
    func heightOfZixun(_ zx: ZixunModel) -> CGFloat {
        
        return ZixunCell.heightWithText(zx.title)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let reuseId = "banner"
            if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) {
                return cell
            }
            let cell = UITableViewCell.init(style: .default, reuseIdentifier: reuseId)
            cell.contentView.backgroundColor = Const.WTM_GRAY
            cell.contentView.addSubview(banner.view)
            return cell
        }else {
            let cell:ZixunCell = tableView.dequeueReusableCell(withIdentifier: "ZixunCell") as! ZixunCell
            let zixun = self.models[indexPath.row - 1]
            cell.setTitle(zixun.title)
            cell.dateLabel.text = zixun.getTime()
            cell.loveCount.text = String(zixun.favourateCount)
            cell.imgView.backgroundColor = Const.WTM_WHITE_SMOKE
            cell.imgView.kf.setImage(with:URL(string:zixun.imageUrl))
            cell.selectionStyle = .none
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            return
        }
        let zixun = self.models[indexPath.row - 1]
        let url = NetworkManager.BASE_URL + NetworkManager.ZIXUN_Detail + zixun.modelId

        let vc:WebViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: WebViewController.VCID) as! WebViewController
        vc.url = url
        vc.shareObj = ShareObject.init()
        let cell:ZixunCell = tableView.cellForRow(at: indexPath) as! ZixunCell
        vc.shareObj?.image = cell.imgView.image
        vc.shareObj?.imageUrl = zixun.imageUrl
        vc.shareObj?.url = url
        vc.shareObj?.title = zixun.title
        vc.title = "资讯详情"
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
